﻿using AutoMapper;
using Cms.Core.Infrastructure.Extension;
using Cms.Core.Infrastructure.Helps;
using Cms.Core.Infrastructure.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Cms.Core.Infrastructure.AutoMapper
{
    public class AutoMapperHelper
    {
        private static void CreateMap(Type type)
        {
            CreateMapping<AutoMapFromAttribute>(type);
            CreateMapping<AutoMapToAttribute>(type);
            CreateMapping<AutoMapAttribute>(type);
        }

        private static void CreateAllMap()
        {
            IAllAssemblyFinder allAssemblyFinder = new RuntimeHelper();
            allAssemblyFinder.FindAll().SelectMany(o => o.GetTypes()).Where(o =>
            o.HasAttribute<AutoMapAttribute>()
         || o.HasAttribute<AutoMapAttribute>()
         || o.HasAttribute<AutoMapToAttribute>()).ToList()
        .ForEach(type =>
        {
            CreateMap(type);
        });

        }
        public static void Register()
        {
            CreateAllMap();
            Mapper.Initialize(x => x.AddProfile<AutoMapperProfile>());      //最后初始化注册一次
        }

        /// <summary>
        /// 创建映射
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <param name="type"></param>

        private static void CreateMapping<TAttribute>(Type type)
            where TAttribute : AutoMapAttribute
        {
            if (!type.IsDefined(typeof(TAttribute)))
            {
                return;
            }

            type.GetCustomAttributes<TAttribute>().Where(o => o.TargetTypes != null).ToList().ForEach(autoMapAttr =>
            {

                autoMapAttr.TargetTypes.ToList().ForEach(targetType =>
                {

                    if (autoMapAttr.Direciton.HasFlag(AutoMapDirection.To))
                    {
                        AutoMapperProfile.AddMapping(type, targetType);
                    }
                    if (autoMapAttr.Direciton.HasFlag(AutoMapDirection.From))
                    {
                        AutoMapperProfile.AddMapping(targetType, type);
                    }
                });
            });
        }
    }

}
